package io.renren.modules.app.controller.user;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.io.FileUtil;
import io.renren.modules.app.entity.info.PositionTypeEntity;
import io.renren.modules.app.entity.info.SalaryEntity;
import io.renren.modules.app.entity.info.UserJobStatusEntity;
import io.renren.modules.app.entity.info.WorkYearEntity;
import io.renren.modules.app.entity.user.*;
import io.renren.modules.app.service.info.PositionTypeService;
import io.renren.modules.app.service.info.SalaryService;
import io.renren.modules.app.service.info.UserJobStatusService;
import io.renren.modules.app.service.info.WorkYearService;
import io.renren.modules.app.service.user.*;
import io.renren.modules.app.utils.FileUploadUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;


/**
 * @author lym
 * @email 928185446qq.com
 * @date 2023-12-19 10:49:13
 */
@RestController
@RequestMapping("/userResume")
public class UserResumeController {

    @Value("${server.port}")
    private String port;
    //个人简历
    @Resource
    private UserResumeService UserResumeService;
    //求职意向
    @Resource
    private UserIntentionJobService UserIntentionJobService;
    //职位种类
    @Resource
    private PositionTypeService positionTypeService;
    //期望薪资
    @Resource
    private SalaryService salaryService;
    // 工作年限
    @Resource
    private WorkYearService workYearService;
    //求职状态
    @Resource
    private UserJobStatusService jobStatusService;

    @Resource
    private UserService userService;
    @Resource
    private UserExperienceService userExperienceService;
    @Resource
    private UserEducationService userEducationService;

    @PostMapping("/upload")
    //上传接口之外上传头像的时候被调用，然后返回了图片链接/上传成功返回的是一个访问图片链接
    //把图片上传提取为一个公共接口
    public R upload(@RequestBody MultipartFile file) {

        try {
            // 获取文件大小
            long sizeNumber = file.getSize();
            // 加上单位
            String size = FileUtil.readableFileSize(sizeNumber);

            //文件名称
            String originalFilename = file.getOriginalFilename();
            //获取最后一个.的位置
            int lastIndexOf = originalFilename.lastIndexOf(".");
            //获取图片的后缀名
            String suffix = originalFilename.substring(lastIndexOf + 1);

            String format = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-"));
            String fileName = format + UUID.randomUUID() + "." + suffix;
            //定义文件的唯一标识（前缀）
            String rootFilePath = System.getProperty("user.dir") + "/src/main/resources/static/file/" + fileName;
            FileUtil.writeBytes(file.getBytes(), rootFilePath);   //把文件写入到上传的路径
            //点击图片上传的时候会先走这个，upload的接口，这个接口走完之后会返给前端一个图片访问地址，
            // 然后填写完简历以后，这个图片访问地址跟着简历信息一起发给下面save接口，然后一起保存到sql里
            return R.ok("http://localhost:" + port + "/file1/" + fileName).put("size", size);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list() {
        Map<String, Object> resultMap = new HashMap<>();
        // 获取职位类型列表
        List<PositionTypeEntity> positionTypeList = positionTypeService.selectList();
        System.out.println(positionTypeList);
        resultMap.put("positionTypeList", positionTypeList);

        // 获取薪资列表
        List<SalaryEntity> salaryList = salaryService.list();
        resultMap.put("salaryList", salaryList);

        // 获取职位状态列表
        List<UserJobStatusEntity> jobStatusList = jobStatusService.list();
        resultMap.put("jobStatusList", jobStatusList);
        List<WorkYearEntity> workYearList = workYearService.list();
        resultMap.put("workYearList", workYearList);

        // 返回包含列表数据的Map
        return R.ok(resultMap);
    }



    /**
     * 查询求职者简历信息是否完善
     */
    @GetMapping("/personResume")
    public R personResume(@RequestParam("userId") Integer userId) {
        UserEntity user = userService.getUserInfoById(userId);
        List<UserResumeEntity> userResume = UserResumeService.selectListByUserId(userId);
        List<UserExperienceEntity> userExperience = userExperienceService.getListByUserId(userId);
        List<UserEducationEntity> userEducation = userEducationService.queryListByUserId(userId);
        List<UserIntentionJobEntity> ycUserIntentionJobList = UserIntentionJobService.queryByUserId(userId);
        return R.ok().put("user", user).put("userResume", userResume)
                .put("userExperience", userExperience)
                .put("userEducation", userEducation)
                .put("ycUserIntentionJobList", ycUserIntentionJobList);
    }

    /**
     * 检测求职者简历是否完善
     */
    @RequestMapping("/checkPersonResume")
    public R checkPersonResume (@RequestParam("userId") Integer userId) {
        if (Objects.nonNull(userId)) {
            List<UserResumeEntity> userResume = UserResumeService.selectListByUserId(userId);
            List<UserExperienceEntity> userExperience = userExperienceService.getListByUserId(userId);
            List<UserEducationEntity> userEducation = userEducationService.queryListByUserId(userId);
            List<UserIntentionJobEntity> ycUserIntentionJobList = UserIntentionJobService.queryByUserId(userId);
            if (userResume.size() > 0 && userExperience.size() > 0
                    && userEducation.size() > 0 && ycUserIntentionJobList.size() > 0) {
                return R.ok().put("data", true);
            }
        }
        return R.ok().put("data", false);
    }

    /**
     * 检测是否已经投递
     */
    @RequestMapping("/checkDeliverVita")
    public R checkDeliverVita (@RequestParam("userId") Integer userId,
            @RequestParam("recruitId") Integer recruitId) {
        return R.ok().put("data", UserResumeService.checkDeliverVita(userId, recruitId));
    }

    /**
     * 投递简历
     */
    @RequestMapping("/doDeliverVita")
    public R doDeliverVita (@RequestParam("userId") Integer userId,
                @RequestParam("recruitId") Integer recruitId) {
        return R.ok().put("data", UserResumeService.doDeliverVita(userId, recruitId));
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id) {
        UserResumeEntity UserResume = UserResumeService.getById(id);

        return R.ok().put("UserResume", UserResume);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    public R save(@RequestBody UserResumeEntity userResume) {
        //根据 ID 查询
        UserEntity user = userService.getById(userResume.getUserId());
        //设置头像
        if (StringUtils.isNotEmpty(userResume.getResumePortrait())) {
            String image = userResume.getResumePortrait();
            String filename = saveImage(image);
            user.setUserPortrait(filename);
            filename = filename.split("/")[1];
            saveImageTarget(image, filename);
        }
        //设置手机号
        user.setMobile(userResume.getTel());
        //设置微信号
        user.setWeixin(userResume.getWechat());
        userService.updateById(user);

        userResume.setResumePortrait(user.getUserPortrait());
        // 设置添加时间
        userResume.setUserName(user.getAccountName());
        userResume.setDeletestatus(false);
        userResume.setAddtime(new Date());
        //sql表有该字段
        userResume.setUpdateTime(new Date());
        // 插入个人简历
        UserResumeService.save(userResume);
        //设置添加时间
        UserIntentionJobEntity userIntentionJob = new UserIntentionJobEntity();
        userIntentionJob.setUserId(userResume.getUserId());
        userIntentionJob.setJobStatus(userResume.getJobStatus());
        userIntentionJob.setDeletestatus(false);
        userIntentionJob.setCityId(userResume.getCityId());
        userIntentionJob.setPositionId(userResume.getPositionType());
        userIntentionJob.setWorkYear(userResume.getWorkYear());
        userIntentionJob.setExpectedSalary(userResume.getResumeSalary());
        userIntentionJob.setAddtime(new Date());
        // 插入求职意向
        UserIntentionJobService.save(userIntentionJob);
        return R.ok();
    }

    /*文件存储地址*/
    @Value("${file.save-path}")//yml的文件上传路径
    private String UPLOAD_SAVE_PATH;

    @Value("${file.target-path}")
    private String UPLOAD_TARGET_PATH;

    /**
     * 生成文件
     */
    private void saveImageTarget (String base64, String filename) {
        if (StringUtils.isNotEmpty(base64) && StringUtils.isNotEmpty(filename)) {
            byte[] decodedBytes = Base64.getDecoder().decode(base64);
            //组装存储路径
            String property = System.getProperty("file.separator");
            String parent_path = LocalDate.now().toString();
            //存贮至编译文件。前端可以直接访问。存到target下面的static的upload下
            String saveFilePath = (UPLOAD_TARGET_PATH + "/" + parent_path + "/").replaceAll("//", property);
            //检测文件路径是否存在
            if (!new File(saveFilePath).exists()) {
                new File(saveFilePath).mkdirs();
            }
            //生成文件名称
            String savePath = (saveFilePath + filename).replaceAll("//", property);
            try (OutputStream out = Files.newOutputStream(new File(savePath).toPath())) {
                out.write(decodedBytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 生成文件
     */
    private String saveImage (String base64) {
        if (StringUtils.isNotEmpty(base64)) {
            byte[] decodedBytes = Base64.getDecoder().decode(base64);//获取base64后转成字节
            //组装存储路径
            String property = System.getProperty("file.separator");//获取系统的路径符号，window是/
            String parent_path = LocalDate.now().toString();//获取当前时间作为文件夹
            String saveFilePath = (UPLOAD_SAVE_PATH + "/" + parent_path + "/").replaceAll("//", property);//拼装文件磁盘存储路径
            //检测文件路径是否存在
            if (!new File(saveFilePath).exists()) {
                new File(saveFilePath).mkdirs();//不存在该路径就创建
            }
            //生成文件名称
            String filename = System.currentTimeMillis() + ".jpg";
            String savePath = (saveFilePath + filename).replaceAll("//", property);//拼装完整的存储路径含有文件名和文件格式
            try (OutputStream out = Files.newOutputStream(new File(savePath).toPath())) {//通过文件流把文件写入到系统文件里
                out.write(decodedBytes);
                return  parent_path + "/" + filename;//fan
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody UserResumeEntity UserResume) {
        UserResumeService.updateById(UserResume);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids) {
        UserResumeService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
